<?php

namespace App\GameChannel\Sdks;

use App\GameChannel\LoginNotify;
use App\GameChannel\PayNotify;
use App\GameChannel\SdkBase;
use App\Models\Orders;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

class H5quickSdk extends SdkBase
{
    public function login(Request $request): LoginNotify
    {
        $notify = $this->loginNotify;

        $token  = $request['access_token'];
        $uid    = $request['openid'];
        $appid  = $this->gameChannel['appid'];

        $url = "http://checkuser.quickapi.net/v2/checkUserInfo";
        $params = [
            'token'        => $token,
            'uid'          => $uid,
            'product_code' => $appid,
        ];

        $response = Http::get($url, $params);
        if (!$response->ok()) {
            $notify->errno = 41159;
            return $notify;
        }

        $body = $response->body();
        if ($body != '1') {
            $notify->errno = 41159;
            return $notify;
        }

        $notify->openid = $uid;

        return $notify;
    }

    // 将xml转为array
    private function fromXml(string $xml)
    {
        $xml = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
        $json = json_encode($xml);
        $data = json_decode($json, true);

        return $data;
    }

    // 处理充值回调
    public function payCb(Request $request, $cb_type): PayNotify
    {
        $notify = $this->payNotify;
        $params = $request->all();
        $data = $this->fromXml($params['nt_data']);

        // 校验订单
        $trade_no = $params['game_order'];
        $order    = Orders::where('trade_no', $trade_no)->first();
        if (!$order) {
            $notify->errno = 6011;
            return $notify;
        }

        // 如果此订单已经被处理过
        if ($order->status != Orders::PAY_STATUS_CREATE) {
            $notify->errno = 6012;
            return $notify;
        }

        // 校验充值金额
        if (abs($order->amount - floatval($params['amount'])) > 1) {
            $notify->errno = 6013;
            return $notify;
        }

        // 校验用户
        if ($order->channel_openid != $params['channel_uid']) {
            $notify->errno = 6014;
            return $notify;
        }

        $notify->order          = $order;
        $notify->tradeNo        = $trade_no;
        $notify->channelTradeNo = $params['order_no'];
        $notify->isTest         = $params['is_test'] == 1?1:0;
        return $notify;
    }

    public function supplementOrderInfo()
    {
        $notify = $this->payNotify;
        $order = $notify->order;
        $order->is_test = $notify->isTest;

        return true;
    }

    public function payOk()
    {
        return 'SUCCESS';
    }

    public function payErr()
    {
        if ($this->payNotify->errno == 6012) {
            return 'SUCCESS';
        }

        return yqerr($this->payNotify->errno);
    }
}
